﻿using System;
using NHibernate;
using NHibernate.Cfg;

namespace DAL
{
    class HibernateSessionFactory
    {
        private static ISessionFactory sessionFactory = null;
        private static ISession session = null;
        static readonly object padlock = new object();

        static HibernateSessionFactory()
        {
            buildSessionFactory();
        }

        public static ISession getSession()
        {
            lock (padlock)
            {
                if (session == null || !session.IsOpen)
                {
                    if (sessionFactory == null || sessionFactory.IsClosed)
                    {
                        buildSessionFactory();
                    }
                    try
                    {
                        session = sessionFactory.OpenSession();
                    }
                    catch
                    {
                        Console.WriteLine("获取Session出错！");
                    }
                }
            }
            return session;
        }

        public static void closeSession()
        {
            lock (padlock)
            {
                if (session != null)
                {
                    try
                    {
                        session.Close();
                    }
                    catch
                    {
                        Console.WriteLine("关闭Session出错！");
                    }
                }
            }
        }

        private static void buildSessionFactory()
        {
            try
            {                
                sessionFactory = new Configuration().Configure().BuildSessionFactory();
            }
            catch
            {
                Console.WriteLine("数据库连接出错！");
            }
        }
    }
}